<template>
  <div class="radio-management-container">
    <Header />
    <div class="content">
      <h2>精品电台管理</h2>
      
      <!-- 新增节目表单 -->
      <div class="program-form">
        <h3>发布新电台节目</h3>
        <form @submit.prevent="submitProgram">
          <div class="form-group">
            <label for="title">节目标题</label>
            <input 
              type="text" 
              id="title" 
              v-model="newProgram.title" 
              required
              placeholder="请输入节目标题"
            >
          </div>
          
          <div class="form-group">
            <label for="description">节目描述</label>
            <textarea 
              id="description" 
              v-model="newProgram.description" 
              required
              placeholder="请输入节目描述"
              rows="3"
            ></textarea>
          </div>
          
          <div class="form-group">
            <label for="coverUrl">封面图片URL</label>
            <input 
              type="url" 
              id="coverUrl" 
              v-model="newProgram.coverUrl" 
              required
              placeholder="请输入封面图片的URL地址"
            >
          </div>
          
          <div class="form-group">
            <label for="audioUrl">公众号链接</label>
            <input 
              type="url" 
              id="audioUrl" 
              v-model="newProgram.audioUrl" 
              required
              placeholder="请输入公众号文章链接"
            >
          </div>
          
          <div class="form-group">
            <label for="duration">节目时长 (格式: 00:00)</label>
            <input 
              type="text" 
              id="duration" 
              v-model="newProgram.duration" 
              required
              placeholder="例如: 05:30"
            >
          </div>
          
          <button type="submit" class="submit-btn">发布节目</button>
        </form>
      </div>
      
      <!-- 节目列表 -->
      <div class="program-list">
        <h3>已发布节目</h3>
        <table class="program-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>标题</th>
              <th>发布时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="program in currentPrograms" :key="program.id">
              <td>{{ program.id }}</td>
              <td>{{ program.title }}</td>
              <td>{{ formatDate(program.publishTime) }}</td>
              <td class="action-buttons">
                <button @click="editProgram(program)" class="edit-btn">编辑</button>
                <button @click="deleteProgram(program.id)" class="delete-btn">删除</button>
              </td>
            </tr>
            <tr v-if="currentPrograms.length === 0">
              <td colspan="4" class="no-data">暂无节目，请发布新节目</td>
            </tr>
          </tbody>
        </table>
        
        <!-- 分页控件 -->
        <div class="pagination" v-if="totalPages > 1">
          <button 
            class="page-btn" 
            @click="currentPage = 1" 
            :disabled="currentPage === 1"
          >
            首页
          </button>
          <button 
            class="page-btn" 
            @click="currentPage--" 
            :disabled="currentPage === 1"
          >
            上一页
          </button>
          
          <span 
            class="page-number" 
            v-for="page in pageNumbers" 
            :key="page"
            @click="currentPage = page"
            :class="{ active: currentPage === page }"
          >
            {{ page }}
          </span>
          
          <button 
            class="page-btn" 
            @click="currentPage++" 
            :disabled="currentPage === totalPages"
          >
            下一页
          </button>
          <button 
            class="page-btn" 
            @click="currentPage = totalPages" 
            :disabled="currentPage === totalPages"
          >
            末页
          </button>
          
          <div class="page-info">
            第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
          </div>
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup>
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import { ref, onMounted, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import axios from 'axios'

const authStore = useAuthStore()
const router = useRouter()

// 检查登录状态和权限
onMounted(() => {
  if (!authStore.isLoggedIn || authStore.user?.role !== 'minister') {
    router.push('/login')
  } else {
    fetchPrograms()
  }
})

// 节目数据
const programs = ref([])
const newProgram = ref({
  title: '',
  description: '',
  coverUrl: '',
  audioUrl: '',
  duration: ''
})
const editingProgram = ref(null)

// 分页相关变量
const currentPage = ref(1)
const pageSize = ref(10) // 每页显示10条数据

// 获取节目列表
const fetchPrograms = async () => {
  try {
    // 实际项目中可以在这里添加分页参数到API请求
    const response = await axios.get('/api/radio/programs')
    programs.value = response.data
    currentPage.value = 1 // 重置到第一页
  } catch (error) {
    console.error('获取节目列表失败:', error)
  }
}

// 提交新节目
const submitProgram = async () => {
  try {
    const programData = {
      ...newProgram.value,
      publishTime: new Date().toISOString()
    }
    
    if (editingProgram.value) {
      // 编辑现有节目
      await axios.put(`/api/radio/programs/${editingProgram.value.id}`, programData)
      const index = programs.value.findIndex(p => p.id === editingProgram.value.id)
      programs.value[index] = { ...programData, id: editingProgram.value.id }
      editingProgram.value = null
    } else {
      // 创建新节目
      const response = await axios.post('/api/radio/programs', programData)
      programs.value.push({ ...response.data, id: programs.value.length + 1 })
    }
    
    // 重置表单
    newProgram.value = {
      title: '',
      description: '',
      coverUrl: '',
      audioUrl: '',
      duration: ''
    }
    
    alert(editingProgram.value ? '节目更新成功' : '节目发布成功')
  } catch (error) {
    console.error('提交节目失败:', error)
    alert('操作失败，请重试')
  }
}

// 编辑节目
const editProgram = (program) => {
  editingProgram.value = program
  newProgram.value = { ...program }
  // 滚动到表单位置
  document.querySelector('.program-form').scrollIntoView({ behavior: 'smooth' })
}

// 删除节目
const deleteProgram = async (id) => {
  if (confirm('确定要删除这个节目吗？')) {
    try {
      await axios.delete(`/api/radio/programs/${id}`)
      programs.value = programs.value.filter(p => p.id !== id)
      
      // 如果删除后当前页没有数据且不是第一页，则返回上一页
      if (currentPrograms.value.length === 0 && currentPage.value > 1) {
        currentPage.value--
      }
      
      alert('节目已删除')
    } catch (error) {
      console.error('删除节目失败:', error)
      alert('删除失败，请重试')
    }
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 分页计算
const totalPages = computed(() => {
  return Math.ceil(programs.value.length / pageSize.value)
})

// 当前页显示的节目
const currentPrograms = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return programs.value.slice(startIndex, endIndex)
})

// 生成页码列表（最多显示5个页码）
const pageNumbers = computed(() => {
  const pages = []
  const maxDisplayed = 5
  
  // 总页数小于等于最大显示数，直接显示所有页码
  if (totalPages.value <= maxDisplayed) {
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i)
    }
  } else {
    // 总页数大于最大显示数，显示当前页附近的页码
    let startPage = Math.max(1, currentPage.value - Math.floor(maxDisplayed / 2))
    let endPage = startPage + maxDisplayed - 1
    
    // 确保结束页不超过总页数
    if (endPage > totalPages.value) {
      endPage = totalPages.value
      startPage = endPage - maxDisplayed + 1
    }
    
    for (let i = startPage; i <= endPage; i++) {
      pages.push(i)
    }
  }
  
  return pages
})
</script>

<style scoped>
.radio-management-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.content {
  flex: 1;
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
  padding: 30px 20px;
}

h2 {
  color: #2c3e50;
  margin-bottom: 30px;
  padding-bottom: 10px;
  border-bottom: 2px solid #3498db;
}

h3 {
  color: #34495e;
  margin: 25px 0 15px;
}

.program-form {
  background: white;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #666;
  font-weight: 500;
}

input, textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

input:focus, textarea:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.submit-btn {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #2980b9;
}

.program-list {
  background: white;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.program-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
}

.program-table th,
.program-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.program-table th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.edit-btn {
  background-color: #52c41a;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  gap: 8px;
  flex-wrap: wrap;
}

.page-btn {
  padding: 5px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
  transition: all 0.2s;
}

.page-btn:hover:not(:disabled) {
  background-color: #f5f7fa;
  border-color: #3498db;
  color: #3498db;
}

.page-btn:disabled {
  cursor: not-allowed;
  opacity: 0.6;
  color: #999;
}

.page-number {
  padding: 5px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.page-number.active {
  background-color: #3498db;
  color: white;
}

.page-number:not(.active):hover {
  background-color: #f5f7fa;
  color: #3498db;
}

.page-info {
  margin-left: 15px;
  color: #666;
  font-size: 14px;
}
</style>
